package com.cyzy.controller;

import com.cyzy.entity.User;
import com.cyzy.service.UserService;
import com.cyzy.util.Result;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/users") // 注意路径是/api/users，而非/api/user
public class UserController {

    @Autowired
    private UserService userService;

    // 原GET接口改为POST，路径保持与类上的@RequestMapping组合为/api/users/list
    @PostMapping("/list")
    public Result<Map<String, Object>> getUsers(@RequestBody Map<String, Object> params) {
        try {
            // 从请求体中获取参数，兼容null情况
            Integer username = null;
            if (params.get("username") != null) {
                if (params.get("username") instanceof Number) {
                    username = ((Number) params.get("username")).intValue();
                } else if (params.get("username") instanceof String) {
                    try {
                        username = Integer.parseInt((String) params.get("username"));
                    } catch (NumberFormatException e) {
                        // 忽略无效的用户名
                    }
                }
            }

            String realName = (String) params.get("realName");
            String phone = (String) params.get("phone");
            int pageNum = params.get("pageNum") != null ? ((Number) params.get("pageNum")).intValue() : 1;
            int pageSize = params.get("pageSize") != null ? ((Number) params.get("pageSize")).intValue() : 10;

            PageInfo<User> pageInfo = userService.getUsers(username, realName, phone, pageNum, pageSize);

            // 处理用户数据，确保不会出现null值导致前端错误
            for (User user : pageInfo.getList()) {
                if (user.getRealNameVerified() == null) {
                    user.setRealNameVerified(0); // 默认设置为未认证
                }
                if (user.getRole() == null) {
                    user.setRole(2); // 默认设置为学生
                }
                if (user.getGender() == null) {
                    user.setGender(0); // 默认设置为未知
                }
            }

            Map<String, Object> result = new HashMap<>();
            result.put("userList", pageInfo.getList());
            result.put("totalUsers", pageInfo.getTotal());
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询用户列表失败: " + e.getMessage());
        }
    }

    // 其他接口保持不变（如果需要也可统一改为POST，此处仅修改列表查询接口）
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Integer id) {
        return Result.success(userService.getUserById(id));
    }

    @PutMapping
    public Result<Boolean> updateUser(@RequestBody User user) {
        return Result.success(userService.updateUser(user));
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> deleteUser(@PathVariable Integer id) {
        return Result.success(userService.deleteUser(id));
    }
}